package com.xy.modulemain.api

import android.util.Log
import com.xy.network.base.NetWorkApi
import com.xy.network.bean.ResponseBean
import com.xy.network.errorhandler.ExceptionHandle
import io.reactivex.functions.Function
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @ClassName MainNetWorkApi
 * @Author xy
 * @Date 2021/8/18 15:51
 * @Description TODO
 */

class MainNetWorkApi() : NetWorkApi() {

    companion object {

        //kotlin 单利
        val instance: MainNetWorkApi by lazy {
            MainNetWorkApi()
        }

        /**
         * 获取服务
         * @param service Class<T>
         * @return T 动态代理的接口
         */
        fun <T> getService(service: Class<T>): T? {
            //动态代理
            Log.i("MainNetWorkApi", "getInstance: $instance")
            return instance.getRetrofit(service)?.create(service)
        }

    }

    override fun getTest(): String {
        return "http://172.27.35.1:8080/"
    }

    override fun getNormal(): String {
        return "http://172.27.35.1:8081/"
    }

    override fun getInterceptor(): Interceptor {
        return object : Interceptor {
            override fun intercept(chain: Interceptor.Chain): Response {
                val newBuilder = chain.request().newBuilder()
                newBuilder.addHeader("os", "moduleMain")
                newBuilder.addHeader("test", "HelloWorld")
                return chain.proceed(newBuilder.build())
            }

        }
    }

    override fun <T> getAppErrorMsgHandler(): Function<T, T> {
        return Function<T, T> {
            if (it is ResponseBean<*> && it.code.isEmpty()) {
                var serverException = ExceptionHandle.ServerException()
                serverException.code = it.code.toInt()
                serverException.message = it.msg
                throw serverException
            }
            it
        }
    }
}